<template>
  <div>
    <van-nav-bar
      title="发布"
      left-text="返回"
      left-arrow
      @click-left="leftClick"
      fixed
      placeholder
    />
    <!-- <div class="zhanwei"></div> -->
    <van-steps :active="active" class="stepsfix">
      <van-step>商品信息</van-step>
      <van-step>商品封面图</van-step>
      <van-step>商品详情图</van-step>
    </van-steps>
    <!-- 商品基本信息 -->
    <van-form @submit="shoponSubmit" v-if="ifshopInfo">
      <van-field
        readonly
        v-model="userId"
        name="userId"
        label="用户ID"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        readonly
        clickable
        name="cateId"
        :value="value"
        label="分类ID"
        placeholder="点击选择分类ID"
        @click="showPicker = true"
      >
      </van-field>

      <van-field
        v-model="goodsTitle"
        name="goodsTitle"
        label="商品标题"
        placeholder="商品标题"
        :rules="[{ required: true, message: '商品标题' }]"
      />

      <van-field
        readonly
        clickable
        name="chengseId"
        :value="csvalue"
        label="成色ID"
        placeholder="请填写成色ID"
        @click="showchengse = true"
      />
      <van-field
        v-model="market"
        name="market"
        label="原价"
        placeholder="原价"
        :rules="[{ required: true, message: '请填写用户名' }]"
      /><van-field
        v-model="price"
        name="price"
        label="现价"
        placeholder="现价"
        :rules="[{ required: true, message: '请填写现价' }]"
      />
      <van-field
        readonly
        clickable
        name="peisongType"
        :value="peisongvalue"
        label="配送ID"
        placeholder="请填写配送ID"
        @click="showpeisong = true"
      />
      <van-field
        v-model="address"
        name="address"
        label="地址"
        placeholder="XX小区|XX学校|xxx"
        :rules="[{ required: true, message: '请填写地址' }]"
      /><van-field
        type="textarea"
        v-model="content"
        name="content"
        label="商品详情"
        placeholder="商品详情"
        :rules="[{ required: true, message: '请填写商品详情' }]"
      /><van-field
        v-model="xm"
        name="xm"
        label="联系人"
        placeholder="联系人"
        :rules="[{ required: true, message: '请填写联系人' }]"
      /><van-field
        v-model="qq"
        name="qq"
        label="qq联系"
        placeholder="qq联系"
        :rules="[{ required: true, message: '请填写qq联系' }]"
      /><van-field
        v-model="wx"
        name="wx"
        label="微信联系"
        placeholder="微信联系"
        :rules="[{ required: true, message: '请填写微信联系' }]"
      />
      <van-field name="goodsStatus" label="商品状态">
        <template #input>
          <van-radio-group v-model="goodsStatus" direction="horizontal">
            <van-radio name="0">下架</van-radio>
            <van-radio name="1">上架</van-radio>
          </van-radio-group>
        </template>
      </van-field>

      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <!-- 封面图的提交 -->
    <van-form @submit="PiconSubmit" v-if="isshopfen">
      <van-field
        v-model="phoType"
        name="phoType"
        label="图类型"
        placeholder="图类型"
        disabled
      />
      <van-field name="phoUrl" label="封面图">
        <template #input>
          <van-uploader
            v-model="fenuploader"
            :after-read="afterRead"
            :max-count="1"
            :before-read="beforeRead"
            :max-size="3000 * 1024"
            @oversize="onOversize"
          />
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
    <!-- 商品图的提交 -->
    <van-form v-if="isshopxiang">
      <van-field
        v-model="shopphoType"
        name="shopphoType"
        label="图类型"
        placeholder="图类型"
        disabled
      />
      <van-field name="phoUrl" label="商品图">
        <template #input>
          <van-uploader
            v-model="shopuploader"
            :after-read="shopafterRead"
            :max-count="3"
            :before-read="shopbeforeRead"
            :max-size="3000 * 1024"
            @oversize="shoponOversize"
          />
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          @click="complete"
          v-if="shopuploader.length"
          >完成</van-button
        >
      </div>
    </van-form>

    <van-popup v-model="showchengse" position="bottom">
      <van-picker
        show-toolbar
        :columns="chenseCols"
        @confirm="csonConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <!-- 成色 -->
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="columns"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
    <!-- 配送  -->
    <van-popup v-model="showpeisong" position="bottom">
      <van-picker
        show-toolbar
        :columns="pscolumns"
        @confirm="psonConfirm"
        @cancel="showpeisong = false"
      />
    </van-popup>
  </div>
</template>

<script>
import $ from "jquery";
import Vue from "vue";
import { Toast } from "vant";

Vue.use(Toast);

export default {
  name: "ToutiaoFabu",

  components: {},

  directives: {},

  data() {
    return {
      shopID: "",
      active: 0,
      // 封面图提交
      phoUrl: "",
      phoType: 1,

      // 商品提交
      shopphoType: 2,
      phoUrl1: "",

      // 步骤判断
      ifshopInfo: true,
      isshopfen: false,
      isshopxiang: false,
      // 图片
      fenuploader: [],
      shopuploader: [],
      cateList: [],
      goodsStatus: "1",
      // 分类
      username: "",
      value: "",
      columns: [],
      showPicker: false,
      // 成色
      csvalue: "",
      showchengse: false,
      chenseCols: [
        "低于五成新",
        "五成新",
        "六成新",
        "七成新",
        "八成新",
        "九成新",
        "全新",
      ],
      // 配送
      peisongvalue: "",
      showpeisong: false,
      pscolumns: ["本地配送", "上门取货", "线上再议"],
      // 商品参数
      userId: "",
      cateId: "",
      goodsTitle: "",
      chengseId: "",
      market: "",
      price: "",
      address: "",
      content: "",
      xm: "",
      qq: "",
      wx: "",
      peisongType: "",
    };
  },

  mounted() {},
  created() {
    this.userId = localStorage.getItem("id");
    this.getCateList();
    // 时间
  },
  methods: {
    leftClick() {
      this.$router.go(-1);
    },
    // 分类
    onConfirm(value) {
      for (let i = 0; i < this.cateList.length; i++) {
        if (this.cateList[i].cateName === value) {
          this.value = this.cateList[i].cateId;
        }
      }
      this.showPicker = false;
    },
    // 成色
    csonConfirm(value, index) {
      this.csvalue = index;
      this.showchengse = false;
    },
    // 配送
    psonConfirm(value, index) {
      this.peisongvalue = index;
      this.showpeisong = false;
    },
    // 获取分类列表
    async getCateList() {
      const { data: res } = await this.$http.get("/api/cate/all");
      //console.log(res);
      this.cateList = res.data;
      let arr = [];
      for (let i = 0; i < res.data.length; i++) {
        let objarr = res.data[i].cateName;
        arr.push(objarr);
      }
      this.columns = arr;
    },
    // shop表单提交
    shoponSubmit(vaules) {
      //console.log(vaules);
      let that = this;
      $.ajax({
        type: "post",
        url: "http://121.4.40.144/api/goods/",
        data: JSON.stringify(vaules),
        dataType: "json",
        contentType: "application/json",
        beforeSend: function (request) {
          request.setRequestHeader("token", localStorage.getItem("token"));
        },
        success: function (res) {
          //console.log(res);

          if (res.code !== 200) {
            Toast("提交失败");
          } else {
            Toast("提交成功");
            that.active = 1;
            that.ifshopInfo = false;
            that.isshopfen = true;
            that.shopID = res.data.goodsId;

            that.userId = "";
            that.cateId = "";
            that.goodsTitle = "";
            that.chengseId = "";
            that.market = "";
            that.price = "";
            that.address = "";
            that.content = "";
            that.xm = "";
            that.qq = "";
            that.wx = "";
            that.peisongType = "";
          }
        },
      });
    },
    // 封面图的提交开始
    PiconSubmit() {
      if (this.phoUrl === "") {
        return Toast("请选择上传的图片");
      }
      let data = {
        phoUrl: this.phoUrl,
        phoType: this.phoType,
        goodsId: this.shopID,
      };
      let that = this;
      $.ajax({
        type: "post",
        url: "http://121.4.40.144/api/photo/",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        beforeSend: function (request) {
          request.setRequestHeader("token", localStorage.getItem("token"));
        },
        success: function (res) {
          //console.log(res);

          if (res.code !== 200) {
            Toast("提交失败");
          } else {
            Toast("提交成功");
            that.isshopfen = false;
            that.isshopxiang = true;
            that.active = 2;
            that.phoUrl = "";
          }
        },
      });
    },
    onOversize(file) {
      Toast("文件大小不能超过 3M");
    },
    beforeRead(file) {
      if (file.type !== "image/jpeg") {
        Toast("请上传 jpg 格式图片");
        return false;
      }
      return true;
    },
    afterRead(file) {
      // 此时可以自行将文件上传至服务器
      let that = this;
      file.status = "uploading";
      file.message = "上传中...";
      //console.log(file);
      var form = new FormData();
      form.append("img", file.file);
      $.ajax({
        type: "POST",
        url: "http://121.4.40.144/api/common/img",
        contentType: "multipart/form-data",
        data: form,
        async: false, //异步
        processData: false, //很重要，告诉jquery不要对form进行处理
        contentType: false, //很重要，指定为false才能形成正确的Content-Type
        success: function (res) {
          //console.log(res);

          if (res.code !== 200) {
            file.status = "failed";
            file.message = "上传失败";
          } else {
            file.status = "done";
            that.phoUrl = res.data;
          }
        },
      });
    },
    // 封面图的提交结束
    shoppiconSubmit() {
      if (this.phoUrl1 === "") {
        return Toast("请选择上传的图片");
      }
      let data = {
        phoUrl: this.phoUrl1,
        phoType: this.shopphoType,
        goodsId: this.shopID,
      };
      let that = this;
      $.ajax({
        type: "post",
        url: "http://121.4.40.144/api/photo/",
        data: JSON.stringify(data),
        dataType: "json",
        contentType: "application/json",
        beforeSend: function (request) {
          request.setRequestHeader("token", localStorage.getItem("token"));
        },
        success: function (res) {
          //console.log(res);
          if (res.code !== 200) {
          } else {
            that.active = 0;
            that.phoUrl1 = "";
          }
        },
      });
    },
    shoponOversize(file) {
      Toast("文件大小不能超过 3M");
    },
    shopbeforeRead(file) {
      if (file.type !== "image/jpeg") {
        Toast("请上传 jpg 格式图片");
        return false;
      }
      return true;
    },
    shopafterRead(file) {
      // 此时可以自行将文件上传至服务器
      let that = this;
      file.status = "uploading";
      file.message = "上传中...";
      //console.log(file);
      var form = new FormData();
      form.append("img", file.file);
      $.ajax({
        type: "POST",
        url: "http://121.4.40.144/api/common/img",
        contentType: "multipart/form-data",
        data: form,
        async: false, //异步
        processData: false, //很重要，告诉jquery不要对form进行处理
        contentType: false, //很重要，指定为false才能形成正确的Content-Type
        success: function (res) {
          //console.log(res);

          if (res.code !== 200) {
            file.status = "failed";
            file.message = "上传失败";
          } else {
            file.status = "done";
            that.phoUrl1 = res.data;
            that.shoppiconSubmit();
          }
        },
      });
    },
    complete() {
      localStorage.removeItem("goodsList");
      this.$router.push({ name: "goods" });
    },
  },
};
</script>

<style lang="less" scoped>
.stepsfix {
  position: fixed;
  top: 35px;
  left: 0px;
  width: 100%;
  z-index: 9;
}
.zhanwei {
  width: 100%;
  height: 40px;
}
</style>